package org.linlinjava.litemall.db.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.app.AppOrderMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.app.ReturnSubOrderGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class LitemallOrderService {
    @Resource
    private LitemallOrderMapper litemallOrderMapper;
    @Resource
    private LitemallOrderItemMapper litemallOrderItemMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private AppOrderMapper appOrderMapper;
    @Autowired
    private LitemallOrderGoodsService litemallOrderGoodsService;
    @Autowired
    private LitemallGoodsService litemallGoodsService;
    @Autowired
    private AgedmallGoodsSettleConfService agedmallGoodsSettleConfService;
    @Autowired
    private AgedmallAgentSettleDetailService agedmallAgentSettleDetailService;
    @Autowired
    private AgedmallGoodsDeductionConfService agedmallGoodsDeductionConfService;
    @Autowired
    private AgedmallDeductDetailService agedmallDeductDetailService;
    @Autowired
    private AgedmallUserInfoService agedmallUserInfoService;
    @Autowired
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;
    @Autowired
    private AgedmallDeliveryManInfoMapper agedmallDeliveryManInfoMapper;
    @Autowired
    private AgedmallLgReceiveOrderMapper agedmallLgReceiveOrderMapper;

    public int add(LitemallOrder order) {
        order.setAddTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        return litemallOrderMapper.insertSelective(order);
    }

    public int addItem(LitemallOrderItem orderItem) {
        orderItem.setAddTime(LocalDateTime.now());
        orderItem.setUpdateTime(LocalDateTime.now());
        return litemallOrderItemMapper.insertSelective(orderItem);
    }

    public LitemallOrderItem getOrderItemByOrderCode(String itemOrderCode) {
        LitemallOrderItemExample litemallOrderItemExample = new LitemallOrderItemExample();
        litemallOrderItemExample.createCriteria().andChildOrderCodeEqualTo(itemOrderCode);
        List<LitemallOrderItem> itemList = litemallOrderItemMapper.selectByExample(litemallOrderItemExample);
        return itemList.size() > 0? itemList.get(0) : null;
    }

    /**
     * 根据大订单号获取大订单信息
     * @param bigOrderCode
     * @return
     */
    public LitemallOrder findOrderByOrderCode(String bigOrderCode) {
        LitemallOrderExample litemallOrderExample = new LitemallOrderExample();
        litemallOrderExample.or().andOrderSnEqualTo(bigOrderCode);
        LitemallOrder litemallOrder = litemallOrderMapper.selectOneByExampleSelective(litemallOrderExample);
        return litemallOrder;
    }

    public int count(Integer userId) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return (int) litemallOrderMapper.countByExample(example);
    }

    public LitemallOrder findById(Integer orderId) {
        return litemallOrderMapper.selectByPrimaryKey(orderId);
    }

    public LitemallOrderItem findItemById(Integer itemOrderId) {
        return litemallOrderItemMapper.selectByPrimaryKey(itemOrderId);
    }

    public List<LitemallOrderItem> findItemListByIds(List<Integer> itemOrderIdList) {
        LitemallOrderItemExample example = new LitemallOrderItemExample();
        example.createCriteria().andIdIn(itemOrderIdList);
        return litemallOrderItemMapper.selectByExample(example);
    }

    public LitemallOrder findById(Integer userId, Integer orderId) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andIdEqualTo(orderId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return litemallOrderMapper.selectOneByExample(example);
    }

    public LitemallOrderItem findItemOrderById(Integer userId, Integer orderId) {
        LitemallOrderItemExample example = new LitemallOrderItemExample();
        example.or().andIdEqualTo(orderId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return litemallOrderItemMapper.selectOneByExample(example);
    }

    private String getRandomNum(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public int countByOrderSn(Integer userId, String orderSn) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andUserIdEqualTo(userId).andOrderSnEqualTo(orderSn).andDeletedEqualTo(false);
        return (int) litemallOrderMapper.countByExample(example);
    }

    // TODO 这里应该产生一个唯一的订单，但是实际上这里仍然存在两个订单相同的可能性
    public String generateOrderSn(Integer userId) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        String now = df.format(LocalDate.now());
        String orderSn = now + getRandomNum(6);
        while (countByOrderSn(userId, orderSn) != 0) {
            orderSn = now + getRandomNum(6);
        }
        return orderSn;
    }

    public List<LitemallOrder> queryByOrderStatus(Integer userId, List<Short> orderStatus, Integer page, Integer limit, String sort, String order) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.setOrderByClause(LitemallOrder.Column.addTime.desc());
        LitemallOrderExample.Criteria criteria = example.or();
        criteria.andUserIdEqualTo(userId);
        if (orderStatus != null) {
            criteria.andOrderStatusIn(orderStatus);
        }
        criteria.andDeletedEqualTo(false);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return litemallOrderMapper.selectByExample(example);
    }

    public List<LitemallOrder> querySelective(Integer userId, String orderSn, LocalDateTime start, LocalDateTime end, List<Short> orderStatusArray, Integer page, Integer limit, String sort, String order) {
        LitemallOrderExample example = new LitemallOrderExample();
        LitemallOrderExample.Criteria criteria = example.createCriteria();

        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!StringUtils.isEmpty(orderSn)) {
            criteria.andOrderSnEqualTo(orderSn);
        }
        if(start != null){
            criteria.andAddTimeGreaterThanOrEqualTo(start);
        }
        if(end != null){
            criteria.andAddTimeLessThanOrEqualTo(end);
        }
        if (orderStatusArray != null && orderStatusArray.size() != 0) {
            criteria.andOrderStatusIn(orderStatusArray);
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return litemallOrderMapper.selectByExample(example);
    }

    public int updateWithOptimisticLocker(LitemallOrder order) {
        LocalDateTime preUpdateTime = order.getUpdateTime();
        order.setUpdateTime(LocalDateTime.now());
        return orderMapper.updateWithOptimisticLocker(preUpdateTime, order);
    }

    public int updateItemWithOptimisticLocker(LitemallOrderItem orderItem) {
        LocalDateTime preUpdateTime = orderItem.getUpdateTime();
        orderItem.setUpdateTime(LocalDateTime.now());
        return orderMapper.updateItemWithOptimisticLocker(preUpdateTime, orderItem);
    }

    public int update(LitemallOrder order) {
        order.setUpdateTime(LocalDateTime.now());
        return litemallOrderMapper.updateByPrimaryKeySelective(order);
    }

    public int updateItem(LitemallOrderItem orderItem) {
        orderItem.setUpdateTime(LocalDateTime.now());
        return litemallOrderItemMapper.updateByPrimaryKeySelective(orderItem);
    }
    public int updateItemByOrderCode(LitemallOrderItem orderItem) {
        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        orderItemExample.createCriteria().andChildOrderCodeEqualTo(orderItem.getChildOrderCode());
        return litemallOrderItemMapper.updateByExampleSelective(orderItem, orderItemExample);
    }

    public void deleteById(Integer id) {
        litemallOrderMapper.logicalDeleteByPrimaryKey(id);
    }

    public int count() {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andDeletedEqualTo(false);
        return (int) litemallOrderMapper.countByExample(example);
    }

    public List<LitemallOrder> queryUnpaid(int minutes) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andOrderStatusEqualTo(OrderUtil.STATUS_CREATE).andDeletedEqualTo(false)
        .andParentIdIsNull();
        return litemallOrderMapper.selectByExample(example);
    }

    public List<LitemallOrderItem> querySaleUnconfirm() {
        List<Short> states = new ArrayList<>();
        states.add(OrderUtil.STATUS_SHIP);
        states.add(OrderUtil.STATUS_SHIP_SELF);
        LitemallOrderItemExample example = new LitemallOrderItemExample();
        example.or().andOrderStatusIn(states)
                .andGoodsTypeEqualTo(GoodsConstant.GOODS_TYPE_SALE)
                .andDeletedEqualTo(false)
                .andParentIdIsNotNull();
        return litemallOrderItemMapper.selectByExample(example);
    }

    public List<LitemallOrderItem> queryLeaseUnconfirm() {
        List<Short> states = new ArrayList<>();
        states.add(OrderUtil.STATUS_SHIP);
        states.add(OrderUtil.STATUS_SHIP_SELF);
        LocalDateTime now = LocalDateTime.now();
        LitemallOrderItemExample example = new LitemallOrderItemExample();
        example.or().andOrderStatusIn(states)
                .andGoodsTypeEqualTo(GoodsConstant.GOODS_TYPE_LEASE)
                .andShipArriveTimeLessThan(now).andDeletedEqualTo(false)
                .andParentIdIsNotNull();
        return litemallOrderItemMapper.selectByExample(example);
    }
    public List<LitemallOrderItem> getOrderItemListByBigOrderCode(String orderCode) {
        LitemallOrderItemExample itemExample = new LitemallOrderItemExample();
        itemExample.createCriteria().andOrderCodeEqualTo(orderCode);
        List<LitemallOrderItem> itemList = litemallOrderItemMapper.selectByExampleSelective(itemExample);
        return itemList;
    }

    public LitemallOrder findBySn(String orderSn) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andOrderSnEqualTo(orderSn).andDeletedEqualTo(false);
        return litemallOrderMapper.selectOneByExample(example);
    }

    public LitemallOrder findBySn(Integer userId, String orderSn) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andDeletedEqualTo(false)
                .andOrderSnEqualTo(orderSn)
                .andUserIdEqualTo(userId);
        return litemallOrderMapper.selectOneByExample(example);
    }

    public LitemallOrderItem findItemBySn(Integer userId, String bigOrderCode, String childOrderCode) {
        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        orderItemExample.createCriteria().andOrderCodeEqualTo(bigOrderCode).andChildOrderCodeEqualTo(childOrderCode).andUserIdEqualTo(userId);
        return litemallOrderItemMapper.selectOneByExampleSelective(orderItemExample);
    }

    public List<LitemallOrder> findListBySn(List<String> orderSns) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andDeletedEqualTo(false)
                .andOrderSnIn(orderSns);
        return litemallOrderMapper.selectByExample(example);
    }
    public List<LitemallOrderItem> findOrderItemListByCodes(List<String> orderCodeList) {
        LitemallOrderItemExample example = new LitemallOrderItemExample();
        example.or().andDeletedEqualTo(false)
                .andChildOrderCodeIn(orderCodeList);
        return litemallOrderItemMapper.selectByExample(example);
    }

    public Map<Object, Object> orderInfo(Integer userId) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<LitemallOrder> orders = litemallOrderMapper.selectByExampleSelective(example, LitemallOrder.Column.orderStatus, LitemallOrder.Column.comments);

        int unpaid = 0;
        int unship = 0;
        int unrecv = 0;
        int uncomment = 0;
        for (LitemallOrder order : orders) {
            if (OrderUtil.isCreateStatus(order)) {
                unpaid++;
            } else if (OrderUtil.isPayStatus(order)) {
                unship++;
            } else if (OrderUtil.isShipStatus(order)) {
                unrecv++;
            } else if (OrderUtil.isConfirmStatus(order) || OrderUtil.isAutoConfirmStatus(order)) {
                uncomment += order.getComments();
            } else {
                // do nothing
            }
        }

        Map<Object, Object> orderInfo = new HashMap<Object, Object>();
        orderInfo.put("unpaid", unpaid);
        orderInfo.put("unship", unship);
        orderInfo.put("unrecv", unrecv);
        orderInfo.put("uncomment", uncomment);
        return orderInfo;

    }

    public List<LitemallOrder> queryComment(int days) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expired = now.minusDays(days);
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andCommentsGreaterThan((short) 0).andConfirmTimeLessThan(expired).andDeletedEqualTo(false);
        return litemallOrderMapper.selectByExample(example);
    }

    public void updateAftersaleStatus(Integer orderId, Short statusReject) {
        LitemallOrder order = new LitemallOrder();
        order.setId(orderId);
        order.setAftersaleStatus(statusReject);
        order.setUpdateTime(LocalDateTime.now());
        litemallOrderMapper.updateByPrimaryKeySelective(order);
    }


    public Map<String, Object> queryVoSelective(String nickname, String consignee, String orderSn, LocalDateTime start, LocalDateTime end, List<Short> orderStatusArray, Integer page, Integer limit, String sort, String order) {
        List<String> querys = new ArrayList<>(4);
        if (!StringUtils.isEmpty(nickname)) {
            querys.add(" u.nickname like '%" + nickname + "%' ");
        }
        if (!StringUtils.isEmpty(consignee)) {
            querys.add(" o.consignee like '%" + consignee + "%' ");
        }
        if (!StringUtils.isEmpty(orderSn)) {
            querys.add(" o.child_order_code = '" + orderSn + "' ");
        }
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (start != null) {
            querys.add(" o.add_time >= '" + df.format(start) + "' ");
        }
        if (end != null) {
            querys.add(" o.add_time < '" + df.format(end) + "' ");
        }
        if (orderStatusArray != null && orderStatusArray.size() > 0) {
            querys.add(" o.order_status in (" + StringUtils.collectionToDelimitedString(orderStatusArray, ",") + ") ");
        }
        querys.add(" o.deleted = 0 and og.deleted = 0 ");
        String query = StringUtils.collectionToDelimitedString(querys, "and");
        String orderByClause = null;
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            orderByClause = "o." + sort + " " + order +", o.id desc ";
        }

        PageHelper.startPage(page, limit);
        Page<Map> list1 = (Page) orderMapper.getOrderIds(query, orderByClause);
        List<Integer> ids = new ArrayList<>();
        for (Map map : list1) {
            Integer id = (Integer) map.get("id");
            ids.add(id);
        }

        List<OrderVo> list2 = new ArrayList<>();
        if (!ids.isEmpty()) {
            querys.add(" o.id in (" + StringUtils.collectionToDelimitedString(ids, ",") + ") ");
            query = StringUtils.collectionToDelimitedString(querys, "and");
            list2 = orderMapper.getOrderList(query, orderByClause);
        }
        Map<String, Object> data = new HashMap<String, Object>(5);
        data.put("list", list2);
        data.put("total", list1.getTotal());
        data.put("page", list1.getPageNum());
        data.put("limit", list1.getPageSize());
        data.put("pages", list1.getPages());
        return data;
    }

    public List<LitemallOrder> orderList(Integer userId, String keyword, List<Short> subOrderStatus, Integer isService, Integer page, Integer limit, String bigOrderId) {
        PageHelper.startPage(page, limit);
        // bigOrderId 服务订单只在第一页显示
        return appOrderMapper.orderList(userId, keyword, subOrderStatus, isService, page == 1 ? bigOrderId : null);
    }

    public List<LitemallOrderItem> sbuOrderList(Integer userId, Integer parentId, List<Short> subOrderStatus, Integer isService) {
        return appOrderMapper.subOrderList(userId, parentId, subOrderStatus, isService);
    }
    public List<LitemallOrderItem> sbuOrderListByChildOrderCode(String childOrderCode) {
        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        orderItemExample.createCriteria().andChildOrderCodeEqualTo(childOrderCode);
        List<LitemallOrderItem> orderItemList = litemallOrderItemMapper.selectByExample(orderItemExample);
        return orderItemList;
    }
    public List<LitemallOrder> queryByPid(Integer parentId) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andDeletedEqualTo(false).andParentIdEqualTo(parentId);
        return litemallOrderMapper.selectByExample(example);
    }

    public List<LitemallOrderItem> queryOrderItemListByBigOrderCode(String bigOrderCode) {
        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        orderItemExample.createCriteria().andOrderCodeEqualTo(bigOrderCode).andDeletedEqualTo(false);
        return litemallOrderItemMapper.selectByExampleSelective(orderItemExample);
    }

    public List<LitemallOrderItem> queryOrderItemListByBigOrderCodeList(List<String> bigOrderCodeList) {
        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        orderItemExample.createCriteria().andOrderCodeIn(bigOrderCodeList).andDeletedEqualTo(false);
        return litemallOrderItemMapper.selectByExampleSelective(orderItemExample);
    }

    public List<LitemallOrderItem> queryOrderItemListByBigOrderIds(List<Integer> bigOrderIdList) {
        if(bigOrderIdList.size() == 0) {
            return new ArrayList<>();
        }
        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        orderItemExample.createCriteria().andParentIdIn(bigOrderIdList).andDeletedEqualTo(false);
        return litemallOrderItemMapper.selectByExampleSelective(orderItemExample);
    }

    public List<LitemallOrderItem> getOrderItemListByBigOrderCode(Integer userId, String bigOrderCode) {
        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        orderItemExample.createCriteria().andUserIdEqualTo(userId).andOrderCodeEqualTo(bigOrderCode).andDeletedEqualTo(false);
        return litemallOrderItemMapper.selectByExampleSelective(orderItemExample);
    }

    public List<LitemallOrder> queryByPidAndStatus(Integer userId, Integer parentId, List<Short> statList) {
        LitemallOrderExample example = new LitemallOrderExample();
        LitemallOrderExample.Criteria criteria = example.or();
        criteria.andDeletedEqualTo(false)
                .andParentIdEqualTo(parentId)
                .andUserIdEqualTo(userId);
        if (!CollectionUtils.isEmpty(statList)) {
            criteria.andOrderStatusIn(statList);
        }
        return litemallOrderMapper.selectByExample(example);
    }

    public List<ReturnSubOrderGoodsVo> getSubOrderListByBigOrderId(Integer userId, Integer bigOrderId, Integer subOrderId) {
        return appOrderMapper.getSubOrderListByBigOrderId(userId, bigOrderId, subOrderId);
    }

    public void updateStatus(Integer orderId, Short status) {
        LitemallOrder order = new LitemallOrder();
        order.setId(orderId);
        order.setOrderStatus(status);
        order.setUpdateTime(LocalDateTime.now());
        litemallOrderMapper.updateByPrimaryKeySelective(order);
    }

    //更新子订单信息
    public void updateLitemallOrderItem(Integer suOrderId,Short status){
        LitemallOrderItem litemallOrderItem = new LitemallOrderItem();
        litemallOrderItem.setId(suOrderId);
        litemallOrderItem.setOrderStatus(status);
        litemallOrderItem.setUpdateTime(LocalDateTime.now());
        litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrderItem);
    }

    //更新 商品信息表商品的状态
    public void updateLitemallOrderGoods(Integer litemallOrderGoodsId,Short status){
        LitemallOrderGoods litemallOrderGoods = new LitemallOrderGoods();
        litemallOrderGoods.setId(litemallOrderGoodsId);
        litemallOrderGoods.setUpdateTime(LocalDateTime.now());
        litemallOrderGoods.setOrderGoodsStat(status.intValue());
        litemallOrderGoodsMapper.updateByPrimaryKeySelective(litemallOrderGoods);
    }


    public void  insertReceiveOrder(Integer ManId,Long baseInfoId,Long missionId,String OrderCode,String shipChannel){
        //配货员信息 接单人信息表
        AgedmallLgReceiveOrder receiveOrder = new AgedmallLgReceiveOrder();
        //配货人员信息
        if (!("".equals(ManId)) && (!"sort".equals(ManId)) && (!"all".equals(ManId))) {
            AgedmallDeliveryManInfo manInfo = agedmallDeliveryManInfoMapper.selectByPrimaryKey(ManId);
            receiveOrder.setUserName(manInfo.getUsername());
            receiveOrder.setPhone(manInfo.getPhone());
            receiveOrder.setLgBaseInfoId(baseInfoId);
            receiveOrder.setMissionId(missionId);
            receiveOrder.setReceiveTime(LocalDateTime.now());
            receiveOrder.setOrderCode(OrderCode);
            receiveOrder.setReceiveType(1);
            if ("".equals(shipChannel)||null==shipChannel){
                //兼职人员
                receiveOrder.setLgExecType(1);
            }else{
                //第三方物流
                receiveOrder.setLgExecType(2);
            }
            receiveOrder.setCreatedTime(LocalDateTime.now());
            receiveOrder.setCreatedBy("auto");
            agedmallLgReceiveOrderMapper.insert(receiveOrder);
        }
    }

    public void updateChildOrderStatus(String itemOrderCode, Short status) {
        LitemallOrderItem orderItem = new LitemallOrderItem();
        orderItem.setChildOrderCode(itemOrderCode);
        orderItem.setOrderStatus(status);
        orderItem.setUpdateTime(LocalDateTime.now());
        LitemallOrderItemExample itemExample = new LitemallOrderItemExample();
        itemExample.createCriteria().andChildOrderCodeEqualTo(itemOrderCode);
        litemallOrderItemMapper.updateByExampleSelective(orderItem, itemExample);
    }

    public void updateNoDepositOrderStatus(String bigOrderCode, Short status) {
        LitemallOrderItem orderItem = new LitemallOrderItem();
        orderItem.setOrderStatus(status);
        orderItem.setUpdateTime(LocalDateTime.now());
        LitemallOrderItemExample itemExample = new LitemallOrderItemExample();
        itemExample.createCriteria().andOrderCodeEqualTo(bigOrderCode).andIsCreditEqualTo(1);
        litemallOrderItemMapper.updateByExampleSelective(orderItem, itemExample);
    }

    public void saveSettle(LitemallOrderItem order, Integer days) {
        //通过订单号获取订单物品的集合
        List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsService.getOrderGoodsListByChildOrderCode(order.getChildOrderCode());
        //判断是否为为卖出
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            if (null == orderGoods.getSaleUserId()) {
                continue;
            }
            AgedmallGoodsSettleConf settleConf = agedmallGoodsSettleConfService.queryByGoodsId(orderGoods.getGoodsId());
            if (null == settleConf) {
                continue;
            }
            BigDecimal proxyPrice = BigDecimal.ZERO;
            LitemallGoods goods = litemallGoodsService.findById(orderGoods.getGoodsId());
            //商品为租赁状态
            if (GoodsConstant.GOODS_TYPE_LEASE.equals(order.getGoodsType())) {
                if (DeductionConfConstant.DED_TYPE_AMOUNT.equals(settleConf.getDedType())) {
                    //计算租赁的价格
                    proxyPrice = settleConf.getDedCoin().multiply(new BigDecimal(days));
                } else {
                    proxyPrice = settleConf.getDedCoin().divide(new BigDecimal(100)).multiply(goods.getDeposit()).multiply(new BigDecimal(days));
                }
                //商品为卖出
            } else {
                if (DeductionConfConstant.DED_TYPE_AMOUNT.equals(settleConf.getDedType())) {
                    proxyPrice = settleConf.getDedCoin();
                } else {
                    proxyPrice = settleConf.getDedCoin().divide(new BigDecimal(100)).multiply(goods.getCounterPrice());
                }
            }
            //计算总价格
            proxyPrice = proxyPrice.multiply(new BigDecimal(orderGoods.getNumber()));
            //通过订单的父id来获取大订单
            LitemallOrder bigOrder = this.findById(order.getParentId());
            AgedmallAgentSettleDetail settleDetail = new AgedmallAgentSettleDetail();
            //更新 settleDetail 的信息
            settleDetail.setUserId(Integer.parseInt(orderGoods.getSaleUserId()));
            settleDetail.setBigOrderSn(bigOrder.getOrderSn());
            settleDetail.setSubOrderSn(order.getChildOrderCode());
            settleDetail.setGoodsId(orderGoods.getGoodsId()+"");
            settleDetail.setItem(AgentSettleDetailConstant.ITEM_INCOME);
            //更新为租赁商品
            if (GoodsConstant.GOODS_TYPE_LEASE.equals(order.getGoodsType())) {
                settleDetail.setItemName(AgentSettleDetailConstant.ITEM_NAME_LEASE);
            } else {
                //更新为售卖商品
                settleDetail.setItemName(AgentSettleDetailConstant.ITEM_NAME_SALE);
            }
            settleDetail.setProxyStatus(AgentSettleDetailConstant.PROXY_STATUS_WAIT);
            //更新订单的价格
            settleDetail.setProxyPrice(proxyPrice);
            //更新交易时间
            settleDetail.setProxyTime(LocalDateTime.now());
            //将更新的订单信息插入到表中
            agedmallAgentSettleDetailService.save(settleDetail);
        }
    }

    public void saveDeduct(LitemallOrderItem order) {
        LitemallOrder bigOrder = this.findOrderByOrderCode(order.getOrderCode());
        List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsService.getOrderGoodsListByChildOrderCode(order.getChildOrderCode());
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            BigDecimal amount = BigDecimal.ZERO;
            LitemallGoods goods = litemallGoodsService.findById(orderGoods.getGoodsId());
            AgedmallGoodsDeductionConf deductionConf = agedmallGoodsDeductionConfService.findDeductionByGoodsId(goods.getId());
            if (null != deductionConf) {
                //按照金额
                if (DeductionConfConstant.DED_TYPE_AMOUNT.equals(deductionConf.getDedType())) {
                    amount = deductionConf.getDedCoin().multiply(new BigDecimal(orderGoods.getNumber()));
                } else {
                    //按照百分比
                    amount = deductionConf.getDedCoin().divide(new BigDecimal(100)).multiply(goods.getCounterPrice()).multiply(new BigDecimal(orderGoods.getNumber()));
                }

                AgedmallDeductDetail deductDetail = new AgedmallDeductDetail();
                deductDetail.setUserId(order.getUserId());
                deductDetail.setType(DeductionConfConstant.TYPE_GET);
                deductDetail.setBigOrderSn(bigOrder.getOrderSn());
                deductDetail.setSubOrderSn(order.getChildOrderCode());
                deductDetail.setGoodsId(goods.getId());
                deductDetail.setAmount(amount);
                agedmallDeductDetailService.save(deductDetail);
            }
            totalAmount = totalAmount.add(amount);
        }

        agedmallUserInfoService.addDeductAmount(order.getUserId(), totalAmount);
    }

    public AgedmallOrderMsg getOrderMsgInfo(Integer orderId) {
        return appOrderMapper.getOrderMsgInfo(orderId);
    }

    public List<LitemallOrderGoods> queryServiceByOid(Integer orderId, Integer isService) {
        return appOrderMapper.queryServiceByOid(orderId, isService);
    }

    public List<LitemallOrderGoods> queryOrderGoodsByBigOrderIds(List<Integer> bigOrderIdList, Integer isService) {
        if(bigOrderIdList.size() == 0) {
            return new ArrayList<>();
        }
        return appOrderMapper.queryOrderGoodsByBigOrderIds(bigOrderIdList, isService);
    }

    public Integer unAftersaleGoodsCount(Integer orderId) {
        return appOrderMapper.unAftersaleGoodsCount(orderId);
    }

    public LitemallOrderItem queryByRfid(String rfid) {
        return appOrderMapper.queryByRfid(rfid);
    }

}
